<template>
	<view class="container">
		<view>
			<u-notice-bar :text="text1"></u-notice-bar>
		</view>

		<view class="flex-between row boxPanel ">
		  <view class="m-r-40">WIFI名称</view>
		  <view class="flex-y-center" >
		    <input type="text" v-model="wifiName" placeholder="请输入WIFI名称" placeholder-class="inputs" >
		  	<text class="m-l-20 color-title2" @click="getCurrentWifi">获取当前WIFI</text>
		  </view>
		</view>
		<view class="flex row boxPanel ">
		  <view class="m-r-40">WIFI密码</view>
		  <view class="flex-y-center" >
		    <input type="password" v-model="wifiPassword" placeholder="请输入密码" placeholder-class="inputs" >
		  </view>
		</view>
		
		<view class="footer fixfooter" :class="{ 'bottom-safe-area': isIphoneX }">
			<view class="submit" @click="submit">确定</view>
		</view>

		<!-- 增加加载弹窗 -->
		<u-overlay :show="showOverlay" @click="showOverlay = false">
			<view class="warp">
				<view class="rect" @tap.stop>
					<view class="flex-y-center m-b-20">
						<u-loading-icon  color="#ff8f33"></u-loading-icon>
						<view class="color-title2 font-30 m-l-20">{{linkTitle}}</view>
					</view>
					<view class=" c-b4">查找设备{{mac_code.slice(-4)}}成功</view>
				</view>
			</view>
		</u-overlay>
		
	</view>
</template>

<script>
	import bluetooth from '@/common/js/bluetooth.js';
	export default {
		data() {
			return {
				isIphoneX: false, //判断手机是否是iphoneX以上
				text1: '使用配网功能时，请确保设备在身旁，手机蓝牙功能已开启，Android手机还需要开启定位功能，设备只支持2.4G的Wi-Fi，请检查Wi-Fi是否是2.4G的',
				wifiName: '',
				wifiPassword: '',
				bluetoothStatus: false, // 蓝牙连接状态
				showOverlay: false,
				linkTitle: '正在准备连接设备', //0：正在准备连接设备  1：正在连接设备f57d中  2：设备f57d正在连接WIFI   3：设备f57d网络配置成功
				mac_code: '',
			}
		},
		onLoad(data) {
		  this.isIphoneX = this.$util.uniappIsIPhoneX()
			// 获取缓存里面的mac_code
			let mac_code = uni.getStorageSync("mac_code");
			if (mac_code) {
				this.mac_code = mac_code;
			}
		},
		onShow() {
			// 获取蓝牙和设备连接状态
			// this.initBluetooth();
		},
		methods: {
			// 获取当前WIFI
			getCurrentWifi() {
				var that = this;
				uni.showLoading({ title: '获取中...' });
				wx.startWifi({
					success (res) {
						// console.log("11111",res)  //res.errMsg startWifi:ok 
						uni.getConnectedWifi({
							success: (res) => {
								// console.log("22222",res)    //errMsg: "getConnectedWifi:ok"
								uni.hideLoading();
								if (res.wifi.SSID) {
									that.wifiName = res.wifi.SSID;
								} else {
									uni.showToast({ title: '未获取到WIFI信息', icon: 'none' });
								}
							},
							fail: (err) => {
								uni.hideLoading();
								uni.showToast({ 
									title: '获取失败: ' + (err.errMsg || '未知错误'), 
									icon: 'none' 
								});
							}
						});
					},
					fail: (err) => {
						uni.hideLoading();
						uni.showToast({ 
							title: '获取失败: ' + (err.errMsg || '未知错误'), 
							icon: 'none' 
						});
					}
				})
				
			},
			
			// 提交表单
			submit() {
				if (!this.wifiName) {
					uni.showToast({ title: '请输入WIFI名称', icon: 'none' });
					return;
				}
				
				if (!this.wifiPassword) {
					uni.showToast({ title: '请输入WIFI密码', icon: 'none' });
					return;
				}
				
				// 存入缓存
				uni.setStorageSync("wifiName", this.wifiName);
				uni.setStorageSync("wifiPassword", this.wifiPassword);

				// 显示加载提示
				this.showOverlay = true;
				this.linkTitle = '正在准备连接设备'; // 状态0
				
				// 蓝牙连接方法-------开始
				this.initBluetooth();
			},
			// 蓝牙连接方法-------开始
			// 获取蓝牙和设备是否已连接
			initBluetooth() {
				let _this = this;
				// 初始化蓝牙
				bluetooth.getBluetoothState().then(() => {
					_this.linkTitle = '正在连接设备'+ this.mac_code.slice(-4) + '中'; // 状态1
					// 搜索外围蓝牙设备
					bluetooth.discoveryBluetooth().then(() => {
						_this.discoveryLoading = true;
						// 获取蓝牙设备
						bluetooth.getBluetoothDevices().then((isHaveDevice) => {
							if (isHaveDevice) {
								console.log("获取蓝牙设备成功",isHaveDevice);
								_this.linkTitle = '设备' + this.mac_code.slice(-4) + '正在连接WIFI'; // 状态2
								// 搜索到指定设备,连接蓝牙
								bluetooth.connectBluetooth().then(() => {
									_this.bluetoothStatus = true;
									_this.linkTitle = '设备' + this.mac_code.slice(-4) + '网络配置成功'; // 状态3
									// setTimeout(() => {
									// 	this.showOverlay = false;
									// }, 1500);
								}, () => {
									_this.bluetoothStatus = false;
									_this.showOverlay = false;
									uni.showToast({ title: '连接失败', icon: 'none' });
								});
							} else {
								// 未搜到设备
								uni.showToast({ title: '查找不到设备', icon: 'none' });
								_this.bluetoothStatus = false;
								_this.showOverlay = false;
							}
						}, () => {
							// 蓝牙搜索失败
							uni.showToast({ title: '查找不到设备', icon: 'none' });
							_this.bluetoothStatus = false;
							_this.showOverlay = false;
						});
					});
				}, () => {
					// 未开启蓝牙
					_this.bluetoothStatus = false;
					_this.showOverlay = false;
				});
			},
			// 向设备发送数据
			writeBlueData() {
				let obj = {
					cmd: 3,
					freq: 430125,
					speakable: 1
				};
				let objStr = JSON.stringify(obj);
				let buffer = new ArrayBuffer(objStr.length); // 每个字符占用2个字节
				let bufView = new Uint8Array(buffer);
				for (let i = 0; i < objStr.length; i++) {
					bufView[i] = objStr.charCodeAt(i);
				}
				bluetooth.writeData(buffer);
			},
			// 蓝牙连接方法-------结束
		
		}
	}
</script>

<style lang="scss" scoped>
.boxPanel {
	padding: 40rpx 24rpx;
}
.row {
	.inputs {
		font-size: 28rpx;
		color: #B8BAC2;
	}
}

.warp {
	display: flex;
	align-items: center;
	justify-content: center;
	height: 100%;
}

.rect {
	display: flex;
	align-items: center;
	justify-content: center;
	flex-direction: column;
	width: 300px;
	height: 160px;
	border-radius: 20rpx;
	background-color: #fff;
}
</style>
